using Unity.Entities;
using Unity.Transforms;
using Unity.Mathematics;
using Unity.Burst;
using UnityEngine;
using static UnityEngine.EventSystems.EventTrigger;

// 移动部分的Job（使用Burst编译）
[BurstCompile]
public partial struct PlayerMovementJob : IJobEntity
{
    public float2 movement; // 输入向量
    public float deltaTime; // 时间增量

    // 仅处理移动逻辑
    public void Execute(ref Translation translation, ref PlayerMovementComponent movementComponent)
    {
        translation.Value += new float3(movement.x, movement.y, 0) * movementComponent.moveSpeed * deltaTime;

        movementComponent.x = movement.x;
        movementComponent.y = movement.y;
    }
}


// 主System（整合输入和Job调度）
public partial class PlayerMovementSystem : SystemBase
{
    protected override void OnUpdate()
    {
        // 1. 获取输入（主线程）
        float2 movement = new float2(
            Input.GetAxis("Horizontal"),
            Input.GetAxis("Vertical")
        );

        // 2. 调度移动Job（并行执行）
        var moveJob = new PlayerMovementJob
        {
            movement = movement,
            deltaTime = Time.DeltaTime
        }.ScheduleParallel();

        // 3. 确保移动Job完成后执行动画
        Dependency = moveJob;
         Entities
            .WithAll<AnimatorComponent, PlayerMovementComponent>()
            .WithoutBurst()
            .ForEach((in AnimatorComponent animatorComponent, in PlayerMovementComponent movementComponent,in SpriteRendererComponent spriteRendererComponent) =>
            {
                // 获取Animator并更新动画状态
                var animator = EntityManager.GetComponentObject<Animator>(animatorComponent.AnimatorEntity);
                float speed = math.length(new float2(movementComponent.x, movementComponent.y));
                if (animator != null)
                {
                    animator.SetBool("IsMoving", speed > 0);
                }
                //人物转向
                var sprite=EntityManager.GetComponentObject<SpriteRenderer>(spriteRendererComponent.fliyEntity);
                bool flag = movementComponent.x < 0;
                sprite.flipX = flag;
            }).Run();
    }
}